package com.ebt.m.proposal_v2.utils;

import android.text.TextUtils;

import com.ebt.m.customer.entity.CustomerDetail;
import com.ebt.m.customer.net.json.CustomerDetailJson;
import com.ebt.m.data.entity.Customer;
import com.ebt.m.data.entity.ProductBridgeObj;
import com.ebt.m.data.middle.InsuranceObj;
import com.ebt.m.data.middle.PolicyNodeMeta;
import com.ebt.m.data.middle.datatype.EController;
import com.ebt.m.commons.model.data.BaseDataResult;
import com.ebt.m.proposal_v2.bean.ApplicantEntity;
import com.ebt.m.proposal_v2.bean.InsuranceEntity;
import com.ebt.m.proposal_v2.bean.InsuranceOption;
import com.ebt.m.proposal_v2.bean.InsuredEntity;
import com.ebt.m.proposal_v2.dao.response.BusinessConfig;
import com.ebt.m.proposal_v2.dao.response.ResponseAttach;
import com.ebt.m.proposal_v2.dao.response.ResponseBrand;
import com.ebt.m.proposal_v2.dao.response.ResponseBrandProduct;
import com.ebt.m.proposal_v2.dao.response.ResponseHistory;
import com.ebt.m.proposal_v2.dao.response.ResponseMain;
import com.ebt.m.proposal_v2.dao.response.ResponseMainDetail;
import com.ebt.m.proposal_v2.retrofit.ResponsePage;
import com.ebt.m.utils.DataValidation;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author archer.qi
 *         Created on 2017/5/12.
 */
public class DataUtils {

    /**
     * Customer -> Applicant
     *
     * @param customer
     * @return
     */
    public static ApplicantEntity toApplicant(Customer customer) {
        if (customer == null) {
            return null;
        }
        return new ApplicantEntity(customer.getCustomerId(), customer.getName(),
                customer.getSex(), customer.getAge(), DateUtils.formatDate(customer.getBirthday()), customer.getCellPhone());
    }

    /**
     * Applicant -> Customer
     *
     * @param applicant
     * @return
     */
    public static Customer toCustomer(ApplicantEntity applicant) {
        if (applicant == null) {
            return null;
        }
        Customer customer = new Customer();
        customer.setCustomerId(applicant.clientAccountId);
        customer.setAge(applicant.age);
        customer.setName(applicant.name);
        customer.setSex(applicant.sex);
        Date date = DateUtils.toDate(applicant.birthday, "yyyy-MM-dd");
        customer.setBirthday(date);
        customer.setCellPhone(applicant.phone);
        return customer;
    }

    /**
     * Customer -> Insured
     *
     * @param customer
     * @return
     */
    public static InsuredEntity toInsured(Customer customer) {
        if (customer == null) {
            return null;
        }
        return new InsuredEntity(customer.getCustomerId(), customer.getName(), customer.getSex(), customer.getAge(),
                DateUtils.formatDate(customer.getBirthday()), customer.getCareerCategory(), customer.getRelationWith());
    }

    /**
     * Insured -> Customer
     *
     * @param insured
     * @return
     */
    public static Customer toCustomer(InsuredEntity insured) {
        if (insured == null) {
            return null;
        }
        Customer customer = new Customer();
        customer.setCustomerId(insured.clientAccountId);
        customer.setName(insured.name);
        customer.setSex(insured.sex);
        customer.setAge(insured.age);
        customer.setBirthday(DateUtils.toDate(insured.birthday, "yyyy-MM-dd"));
        customer.setCareerCategory(insured.profession);
        customer.setRelationWith(insured.relation);
        return customer;
    }

    /**
     * ResponseAttach -> InsuranceEntity
     *
     * @param attach
     * @return
     */
    public static InsuranceEntity toInsuranceEntity(ResponseAttach attach) {
        if (attach == null) {
            return null;
        }
        InsuranceEntity target = new InsuranceEntity();
        target.productId = attach.productId;
        target.productName = attach.productName;
        target.thumbnail = attach.thumbnail;
        target.isMain = 0;
        target.sort = 0;

        target.isEnabled = attach.isEnable == 1;
        target.waringMessage = attach.warnMsg;

        target.featureData = attach.options;
        target.parseFeatureData();

        target.planCode = attach.planCode;
        target.riskType = attach.riskType;
        target.exemptPerson = attach.exemptPerson;
        target.exemptProduct = attach.exemptProduct;

        target.accSex = attach.accSex;
        target.accMinAge = attach.accMinAge;
        target.accMaxAge = attach.accMaxAge;
        target.accOccupation = attach.accOccupation;

        return target;
    }

    /**
     * ResponseAttach列表 -> InsuranceEntity列表
     *
     * @param attaches
     * @return
     */
    public static List<InsuranceEntity> toInsuranceEntityList(List<ResponseAttach> attaches) {
        if (attaches == null || attaches.size() == 0) {
            return null;
        }
        List<InsuranceEntity> targets = new ArrayList<>();
        for (ResponseAttach entity : attaches) {
            InsuranceEntity data = toInsuranceEntity(entity);
            if (data != null) {
                targets.add(data);
            }
        }
        return targets;
    }

    /**
     * 主险详情 -> 主险实体
     *
     * @param rmd
     * @return
     */
    public static List<InsuranceEntity> toInsuranceList(ResponseMainDetail rmd) {
        if (rmd == null) {
            return null;
        }
        List<InsuranceEntity> list = new ArrayList<>();

        InsuranceEntity mainEntity = new InsuranceEntity();

        mainEntity.accOccupation = rmd.getAccOccupation();
        mainEntity.accMaxAge = rmd.getAccMaxAge();
        mainEntity.accMinAge = rmd.getAccMinAge();
        mainEntity.accSex = rmd.getAccSex();

        mainEntity.brandId = rmd.getBrandId();
        mainEntity.productId = rmd.getProductId();
        mainEntity.productName = rmd.getName();
        mainEntity.isMain = 1;
        mainEntity.isBindingMain = false; // 主险该字段设为false，可删除
        mainEntity.thumbnail = rmd.getThumbnail();
        mainEntity.description = rmd.getDescription();
        mainEntity.planCode = rmd.getProductCode();
        mainEntity.featureData = rmd.getOptions();
        if (rmd.getBusinessConfig() != null){
            BusinessConfig businessConfig = new BusinessConfig();
            businessConfig.proposal_maxInsured = rmd.getBusinessConfig().proposal_maxInsured;
            businessConfig.proposal_minInsured = rmd.getBusinessConfig().proposal_minInsured;
            businessConfig.proposal_supportMultipleInsured = rmd.getBusinessConfig().proposal_supportMultipleInsured;
            businessConfig.proposal_other_insured = rmd.getBusinessConfig().proposal_other_insured;
            mainEntity.setBusinessConfig(businessConfig);
        }
        mainEntity.parseFeatureData();

        list.add(mainEntity);

        List<ResponseAttach> attaches = rmd.getNecessaryAddRisk();
        if (ArrayUtils.isEmpty(attaches)) {
            return list;
        }

        for (ResponseAttach att : attaches) {
            if (att != null) {
                InsuranceEntity attachEntity = new InsuranceEntity();
                attachEntity.productId = att.productId;
                attachEntity.productName = att.productName;
                attachEntity.isMain = 0;
                attachEntity.isBindingMain = true;
                attachEntity.thumbnail = att.thumbnail;

                attachEntity.featureData = att.options;
                attachEntity.parseFeatureData();

                attachEntity.riskType = att.riskType;
                attachEntity.planCode = att.planCode;
                attachEntity.exemptPerson = att.exemptPerson;
                attachEntity.exemptProduct = att.exemptProduct;

                attachEntity.isEnabled = att.isEnable == 1;
                attachEntity.waringMessage = att.warnMsg;
                //TODO WANG 主险和附加险的acc限制条件会有不同吗？
                attachEntity.accSex = att.accSex;
                attachEntity.accMinAge = att.accMinAge;
                attachEntity.accMaxAge = att.accMaxAge;
                attachEntity.accOccupation = att.accOccupation;

                list.add(attachEntity);
            }
        }
        return list;
    }

    /**
     * 主险详情 -> 主险实体
     *
     * @param rmd
     * @return
     */
    public static List<InsuranceEntity> toInsuranceList(InsuranceEntity main, ResponseMainDetail rmd) {
        if (rmd == null) {
            return null;
        }
        List<InsuranceEntity> list = new ArrayList<>();

        if (main == null) {
            InsuranceEntity mainEntity = new InsuranceEntity();
            mainEntity.brandId = rmd.getBrandId();
            mainEntity.productId = rmd.getProductId();
            mainEntity.productName = rmd.getName();
            mainEntity.isMain = 1;

            mainEntity.planCode = rmd.getProductCode();

            mainEntity.isBindingMain = false; // 主险该字段设为false，可删除
            mainEntity.thumbnail = rmd.getThumbnail();
            mainEntity.description = rmd.getDescription();

            mainEntity.featureData = rmd.getOptions();
            mainEntity.parseFeatureData();

            mainEntity.sort = 0;

            list.add(mainEntity);
        } else {
            main.planCode = rmd.getProductCode();
            main.brandId = rmd.getBrandId();
            main.sort = 0;
            main.thumbnail = rmd.getThumbnail();
            main.description = rmd.getDescription();
            list.add(main);
        }

        List<ResponseAttach> attaches = rmd.getNecessaryAddRisk();
        if (ArrayUtils.isEmpty(attaches)) {
            return list;
        }

        for (ResponseAttach att : attaches) {
            if (att != null) {
                InsuranceEntity attachEntity = new InsuranceEntity();
                attachEntity.productId = att.productId;
                attachEntity.productName = att.productName;
                attachEntity.isMain = 0;
                attachEntity.isBindingMain = true;
                attachEntity.thumbnail = att.thumbnail;

                attachEntity.sort = list.size();

                attachEntity.featureData = att.options;
                attachEntity.parseFeatureData();

                attachEntity.planCode = att.planCode;
                attachEntity.riskType = att.riskType;
                attachEntity.exemptProduct = att.exemptProduct;
                attachEntity.exemptPerson = att.exemptPerson;

                attachEntity.isEnabled = att.isEnable == 1;
                attachEntity.waringMessage = att.warnMsg;
                list.add(attachEntity);
            }
        }
        return list;
    }

    /**
     * 主险详情 -> 主险实体
     *
     * @param rmd
     * @return
     */
    public static List<InsuranceEntity> convertToInsuranceList(ResponseMainDetail rmd) {
        if (rmd == null) {
            return null;
        }
        List<InsuranceEntity> list = new ArrayList<>();
        InsuranceEntity mainEntity = new InsuranceEntity();
        mainEntity.brandId = rmd.getBrandId();
        mainEntity.productId = rmd.getProductId();
        mainEntity.productName = rmd.getName();
        mainEntity.isMain = 1;
        mainEntity.planCode = rmd.getProductCode();
        mainEntity.isBindingMain = false; // 主险该字段设为false，可删除
        mainEntity.thumbnail = rmd.getThumbnail();
        mainEntity.description = rmd.getDescription();
        mainEntity.featureData = rmd.getOptions();
        mainEntity.parseFeatureData();
        mainEntity.sort = 0;
        mainEntity.accMaxAge = rmd.getAccMaxAge();
        mainEntity.accMinAge = rmd.getAccMinAge();
        mainEntity.accOccupation = rmd.getAccOccupation();
        mainEntity.accSex = rmd.getAccSex();

        mainEntity.setBusinessConfig(rmd.getBusinessConfig());
        list.add(mainEntity);

        List<ResponseAttach> attaches = rmd.getNecessaryAddRisk();
        if (ArrayUtils.isEmpty(attaches)) {
            return list;
        }

        for (ResponseAttach att : attaches) {
            if (att != null) {
                InsuranceEntity attachEntity = new InsuranceEntity();
                attachEntity.productId = att.productId;
                attachEntity.productName = att.productName;
                attachEntity.isMain = 0;
                attachEntity.isBindingMain = true;
                attachEntity.thumbnail = att.thumbnail;

                attachEntity.sort = list.size();

                attachEntity.featureData = att.options;
                attachEntity.parseFeatureData();

                attachEntity.planCode = att.planCode;
                attachEntity.riskType = att.riskType;
                attachEntity.exemptProduct = att.exemptProduct;
                attachEntity.exemptPerson = att.exemptPerson;

                attachEntity.isEnabled = att.isEnable == 1;
                attachEntity.waringMessage = att.warnMsg;

                attachEntity.accMaxAge = att.accMaxAge;
                attachEntity.accMinAge = att.accMinAge;
                attachEntity.accOccupation = att.accOccupation;
                attachEntity.accSex = att.accSex;

                list.add(attachEntity);
            }
        }
        return list;
    }

    public static ResponseMain toResponseMain(ResponseBrandProduct data) {
        if (data == null) {
            return null;
        }
        ResponseMain rm = new ResponseMain();
        rm.productId = data.getProductId();
        rm.shortName = data.getProductName();
        rm.name = data.getProductName();
        rm.isEnable = data.getIsEnable();
        rm.warnMsg = data.getWarnMsg();
        rm.brandId = data.getBrandId();
        rm.brandShortName = data.getBrandShortName();
        rm.brandName = data.getBrandName();
        rm.tagInfo = data.getTagInfo();
        rm.isOpenInsurance = data.getIsOpenInsurance();
        rm.insuranceUrl = data.getInsuranceUrl();
        return rm;
    }

    public static List<ResponseMain> toResponseMainList(List<ResponseBrandProduct> list) {
        if (ArrayUtils.isEmpty(list)) {
            return null;
        }
        List<ResponseMain> targetList = new ArrayList<>();
        for (ResponseBrandProduct rbp : list) {
            if (rbp != null) {
                targetList.add(toResponseMain(rbp));
            }
        }
        return targetList;
    }


    public static ResponseBrand toResponseBrand(ResponseHistory history) {
        if (history == null || TextUtils.isEmpty(history.getSearchId())) {
            return null;
        }
        ResponseBrand brand = new ResponseBrand();
        brand.brandId = Integer.parseInt(history.getSearchId());
        brand.brandShortName = history.getKeyword();
        brand.brandName = history.getKeyword();
        return brand;
    }

    public static List<ResponseBrand> toResponseBrandList(List<ResponseHistory> histories) {
        if (histories == null || histories.size() == 0) {
            return null;
        }
        List<ResponseBrand> target = new ArrayList<>();
        for (ResponseHistory h : histories) {
            if (h != null) {
                target.add(toResponseBrand(h));
            }
        }
        return target;
    }

    public static CustomerDetail toCustomerDetail(Customer customer) {
        if (customer == null) {
            return null;
        }
        CustomerDetail detail = new CustomerDetail();
        detail.setCustomerId(customer.getCustomerId());
        detail.setName(customer.getName());
        if (TextUtils.isEmpty(customer.getNamePrefix())) {
            detail.setNamePrefix(TextUtils.isEmpty(customer.getName()) ? "#" : customer.getName().substring(0, 1));
        } else {
            detail.setNamePrefix(customer.getNamePrefix());
        }
        detail.setSex(customer.getSex());
        detail.setAge(customer.getAge());
        detail.setBirthday(customer.getBirthday() == null ? 0 : customer.getBirthday().getTime());
        if (customer.getBirthday() != null) {
            detail.setIsConfirm(1);
        } else {
            /* isConfirm = 0, 则不显示生日，用于生日为空的情况*/
            detail.setIsConfirm(0);
            /* 如果生日为空，把年龄附加到生日中；客户的年龄是从生日中解析的*/
            detail.setBirthday(DataUtils.getBirthday0ByAge(customer.getAge()));
        }

        detail.setMarriage(customer.getIsMarrage());
        detail.setEducationGrading(customer.getEducationGrading() == null ? 0 : Integer.parseInt(customer.getEducationGrading()));
        detail.setPortraitPath(customer.getPortraitPath());
        detail.setCareerCategory(customer.getCareerCategory());
        detail.setTag(customer.getTag());
        detail.setImportContact(customer.getImportContact());
        return detail;
    }

    public static Customer toCustomer(CustomerDetail detail) {
        if (detail == null) {
            return null;
        }
        Customer customer = new Customer();
        customer.setCustomerId(detail.getCustomerId());
        customer.setName(detail.getName());
        Date birthdayDate = new Date(detail.getBirthday());
        if (detail.getBirthday() == 0) {
            customer.setAge(detail.getAge());
        } else {
            customer.setAge(DateUtils.getAgeByActualBirthday(birthdayDate));
        }
        customer.setBirthday(birthdayDate);
        customer.setSex(detail.getSex());
        customer.setCareerCategory(detail.getCareerCategory());
        customer.setIsConfirm(detail.getIsConfirm());
        customer.setCellPhone(detail.getContactPhone());
        return customer;
    }

    /**
     * 重新格式化getCustomerDetail返回的数据
     *
     * @param customerDetailJson
     */
    public static void reformatCustomerDetailReturn(CustomerDetailJson customerDetailJson) {
         /* 接口返回的单位是秒，转换为毫秒*/
        customerDetailJson.data.setBirthday(customerDetailJson.data.getBirthday() * 1000);
        /* 接口没返回年龄，需要自己计算*/
        long birthdayMillis = customerDetailJson.data.getBirthday();
        Calendar calendar = Calendar.getInstance();
        int thisYear = calendar.get(Calendar.YEAR);
        calendar.setTimeInMillis(birthdayMillis);
        int birthdayYear = calendar.get(Calendar.YEAR);
        customerDetailJson.data.setAge(thisYear - birthdayYear);
    }

    /**
     * 请求主险、附加险时，在年龄 = 0时，需要用birthday对年龄进行一定规则的封装
     *
     * @param age
     * @param birthday
     * @return
     */
    public static String formatRequestParamAge(String age, String birthday) {
        if (TextUtils.isEmpty(age)) {
            return "30";
        }
        int ageValue = Integer.valueOf(age);
        if (ageValue > 0) {
            return age;
        }
        if (TextUtils.isEmpty(birthday)) {
            return "0.00000";
        }
        StringBuffer stringBuffer = new StringBuffer("0.00");

        int days = 0;
        try {
            days = DateUtils.getDayDiffByNow(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        if (days > 99) {
            stringBuffer.append(days);
        } else if (days > 9) {
            stringBuffer.append("0").append(days);
        } else if (days > 0) {
            stringBuffer.append("00").append(days);
        } else {
            stringBuffer.append("000");
        }

        return stringBuffer.toString();
    }

    /**
     * 请求主险、附加险时，在年龄 = 0时，需要用birthday对年龄进行一定规则的封装
     *
     * @param age
     * @param birthday
     * @return
     */
    public static String formatRequestParamAge(String age, Date birthday) {
        if (TextUtils.isEmpty(age)) {
            return "30";
        }
        int ageValue = Integer.valueOf(age);
        if (ageValue > 0) {
            return age;
        }
        if (birthday == null) {
            return "0.00000";
        }
        StringBuffer stringBuffer = new StringBuffer("0.00");

        int days = DateUtils.getDayDiffByNow(birthday);

        if (days > 99) {
            stringBuffer.append(days);
        } else if (days > 9) {
            stringBuffer.append("0").append(days);
        } else if (days > 0) {
            stringBuffer.append("00").append(days);
        } else {
            stringBuffer.append("000");
        }

        return stringBuffer.toString();
    }

    /**
     * 获取录音时长
     *
     * @param millis
     * @return
     */
    public static long getRecordDuration(long millis) {
        if (millis % 1000 > 0) {
            return millis / 1000 + 1;
        }
        return millis / 1000;
    }

    /**
     * 根据年龄获取生日
     * <p>
     * 客户中不存在年龄字段，年龄从生日字段取
     * 因此在创建客户或更新时，如果生日为空时，需要把年龄附加到生日中；生日默认1月1日
     *
     * @param age
     * @return
     */
    public static long getBirthday0ByAge(int age) {
        int year = DateUtils.thisYear();
        int birthdayYear = year - age;
        Calendar c = Calendar.getInstance();
        c.set(birthdayYear, 0, 1);
        return c.getTimeInMillis();
    }

    /***************************************
     * ProductBridgeObj解析
     * ************************************/

    /**
     * 根据fieldName获得单个节点
     *
     * @param
     * @return PolicyNodeMeta
     * @throws
     * @Description: 根据fieldName获得单个节点
     */
    public static PolicyNodeMeta getNodeByFieldName(String fieldName, List<PolicyNodeMeta> list) {
        if (DataValidation.isEmpty(fieldName)) {
            return null;
        }
        PolicyNodeMeta pnm = null;
        for (int i = 0; i < list.size(); i++) {
            pnm = list.get(i);
            if (pnm != null && fieldName.equalsIgnoreCase(pnm.getFieldName())) {
                return pnm;
            }
        }
        return null;
    }

    /**
     * 不使用科学计数法格式化数据
     *
     * @param value
     * @return
     */
    public static String formatGroupingUsed(double value) {
        NumberFormat format = NumberFormat.getInstance();
        format.setGroupingUsed(false);
        return format.format(value);
    }

    /**
     * 保额
     *
     * @param obj
     * @return
     */
    public static InsuranceOption getCoverage(ProductBridgeObj obj) {
        if (obj == null) {
            return null;
        }
        String coverage = formatGroupingUsed(obj.getCoverage());
        InsuranceOption option = new InsuranceOption();
        option.fieldName = "Coverage";
        option.displayName = coverage;
        option.value = coverage;

        /*取保额别名*/
        if (obj.getInsuranceObj() != null && obj.getInsuranceObj().isFenshu()) {
            PolicyNodeMeta node = obj.getInsuranceObj().getUseAnotherFieldNameValue();
            if (node != null) {
                EController ec = (EController) node.getEBTValue();
                option.displayName = ec.getSelectedName();
            }
        }

        return option;
    }

    /**
     * 保费
     *
     * @param obj
     * @return
     */

    public static InsuranceOption getPremium(ProductBridgeObj obj) {
        if (obj == null) {
            return null;
        }
        String premium = formatGroupingUsed(obj.getPremium());
        InsuranceOption option = new InsuranceOption();
        option.fieldName = "Premium";
        option.displayName = premium;
        option.value = premium;
        return option;
    }

    /**
     * 保障期间
     *
     * @param obj
     * @return
     */
    public static InsuranceOption getCoveragePeriod(ProductBridgeObj obj) {
        if (obj == null) {
            return null;
        }
        InsuranceOption option = new InsuranceOption();
        option.fieldName = "CoveragePeriod";
        InsuranceObj mInsuranceObj = obj.getInsuranceObj();
        List<PolicyNodeMeta> list = mInsuranceObj.getControllerNode();
        PolicyNodeMeta node = getNodeByFieldName("CoveragePeriod", list);
        if (node != null) {
            EController ec = (EController) node.getEBTValue();
            option.displayName = ec.getItemDisPlay()[ec.getSelectedIndex()];
            option.value = DataUtils.getIntValue(ec.getItems()[ec.getSelectedIndex()]);
        }
        return option;
    }

    /**
     * 缴费期间
     *
     * @param obj
     * @return
     */
    public static InsuranceOption getPaymentPeriod(ProductBridgeObj obj) {
        if (obj == null) {
            return null;
        }
        InsuranceOption option = new InsuranceOption();
        option.fieldName = "PaymentPeriod";
        InsuranceObj mInsuranceObj = obj.getInsuranceObj();
        List<PolicyNodeMeta> list = mInsuranceObj.getControllerNode();
        PolicyNodeMeta node = getNodeByFieldName("PaymentPeriod", list);
        if (node != null) {
            EController ec = (EController) node.getEBTValue();
            option.displayName = ec.getItemDisPlay()[ec.getSelectedIndex()];
            option.value = ec.getItems()[ec.getSelectedIndex()] + "";
        }
        return option;
    }

    /****************************************************/

    /**
     * 检查Url是否带有参数
     *
     * @param url
     * @return
     */
    public static String addUrlParam(String url, String param) {
        if ((url == null || url.length() == 0) ||
                (param == null || param.length() == 0)) {
            return url;
        }
        if (!url.contains("?")) {
            // 不附带参数
            return url + "?" + param;
        }
        if (url.endsWith("?")) {
            // 不附带参数，且返回了？
            return url + param;
        }
        // 带有？且？不在最后，则带有参数
        return url + "&" + param;
    }

    /**
     * double整值去.0
     *
     * @param value
     * @return
     */
    public static String getIntValue(double value) {
        int intValue = (int) value;
        double difValue = value - intValue;
        if (difValue == 0) {
            return String.valueOf(intValue);
        } else {
            return String.valueOf(value);
        }
    }

    public static String parseIntValue(String value) {
        if (TextUtils.isEmpty(value)) {
            return "0";
        }
        boolean isNumber = isNumberFormat(value);
        if (!isNumber) {
            return value;
        }
        try {
            double originalValue = Double.valueOf(value);
            return getIntValue(originalValue);
        } catch (NumberFormatException e) {
            return "0";
        }
    }

    /**
     * Url参数转码
     *
     * @param pValue
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String encodeParamValue(String pValue) throws UnsupportedEncodingException {
        if (TextUtils.isEmpty(pValue)) {
            return "";
        }
        return URLEncoder.encode(pValue, "utf-8");
    }

    /**
     * 是否是数字格式
     *
     * @param str
     * @return
     */
    public static boolean isNumberFormat(String str) {
        final String REGEX_INT = "^-?\\d+$";
        final String REGEX_FLOAT = "^(-?\\d+)(\\.\\d+)?$";
        return Pattern.compile(REGEX_INT).matcher(str).find() || Pattern.compile(REGEX_FLOAT).matcher(str).find();
    }

    /**
     * 从ProductBridgeObj中解析除四个基本属性之外的多余属性
     *
     * @param productBridgeObj
     * @return
     */
    public static List<InsuranceOption> parseExtraOptions(ProductBridgeObj productBridgeObj) {
        if (productBridgeObj == null || TextUtils.isEmpty(productBridgeObj.getFavoriteJson())) {
            return null;
        }
        String json = productBridgeObj.getFavoriteJson();
        List<InsuranceOption> mExtraOptions = new ArrayList<>();
        try {
            JSONObject obj = new JSONObject(json);
            JSONArray items = obj.optJSONArray("items");
            for (int i = 0; i < items.length(); i++) {
                JSONObject item = items.getJSONObject(i);
                if (item == null) {
                    continue;
                }
                String fieldName = item.optString("FieldName");
                if ("CoveragePeriod".equals(fieldName) || "PaymentPeriod".equals(fieldName)
                        || "Coverage".equals(fieldName) || "Premium".equals(fieldName)) {
                    // 过滤保额，保费，保障期间，缴费期间四个基本选项
                    continue;
                }
                InsuranceOption extraOption = new InsuranceOption();
                extraOption.fieldName = fieldName;
                extraOption.displayName = item.optString("ItemName");
                extraOption.value = item.optString("Value");
                mExtraOptions.add(extraOption);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return mExtraOptions;
    }

    public static BaseDataResult.PageInfo convertPageInfo(ResponsePage page) {
        if (page == null) {
            return null;
        }
        BaseDataResult.PageInfo pInfo = new BaseDataResult().new PageInfo();
        pInfo.setPage(page.page);
        pInfo.setPageSize(page.pageSize);
        pInfo.setHasMore(page.hasMore);
        pInfo.setTotal(page.total);
        return pInfo;
    }

    /**
     * 从产品详情提取出默认投被保人信息
     *
     * @param detail
     * @return
     */
    public static Customer extractCustomer(ResponseMainDetail detail) {
        if (detail == null || detail.getDefaultInsured() == null) {
            return null;
        }
        ResponseMainDetail.DefaultInsuredBean defaultInsured = detail.getDefaultInsured();
        Customer customer = new Customer();
        customer.setCareerCategory(defaultInsured.getProfession());
        customer.setSex(defaultInsured.getSex());
        customer.setAge((int)defaultInsured.getAge());
        if (defaultInsured.getAge() <1 ) {
            customer.setBirthday(getBirthdayByAge(defaultInsured.getAge()));
        }
        return customer;
    }

    public static Date getBirthdayByAge(float age) {
        long currentDay = (long)(age * 100000);
        Date originDate = new Date();
        long birthdayTime = originDate.getTime() - currentDay *60 * 60 * 24 * 1000;
        return new Date(birthdayTime);
    }
}
